//
//  AYSSearchViewController.m
//  AiYingShiProject
//
//  Created by lanou on 15/11/5.
//  Copyright (c) 2015年 李晓理. All rights reserved.
//

#import "AYSSearchViewController.h"
#import "AYSHomeSearchBarTableVC.h"
#import "AYSRequestManager.h"
#import "AYSHomeSearchBarModel.h"
#import "FMDatabase.h"
#import "AYSHomeSDViewController.h"
#import "AYSSideViewController.h"
#import "AppDelegate.h"
@interface AYSSearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UISearchBar *searchBar;
@property(nonatomic, strong)UIButton *searchButton;
@property(nonatomic, strong)AYSHomeSearchBarTableVC *searchBarVC;
@property(nonatomic, strong)NSMutableArray *searchArr;
@property(nonatomic, strong)UITableView *mainTableView;
@property(nonatomic, strong)UIButton *cancleButton;
@property(nonatomic, strong)NSMutableArray *historyArr;

@property(nonatomic, strong)UIButton *homeButton;
// 实现数据持久化
@property(nonatomic, strong)FMDatabase *dataBase;// 数据库
@property(nonatomic, strong)UIView *views;// 表头
@end

@implementation AYSSearchViewController

- (NSMutableArray *)historyArr
{
    if (!_historyArr)
    {
        self.historyArr = [NSMutableArray arrayWithArray:0];
    }
    return _historyArr;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor blackColor];
     self.navigationController.navigationBar.hidden = YES;
    

//    UIColor *color = [UIColor whiteColor];
//    NSDictionary *dict = [NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];
//    self.navigationController.navigationBar.titleTextAttributes = dict;
//    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    _searchArr = [NSMutableArray arrayWithCapacity:0];
    [self useSQLite];
    [self getMainTableView];
    [self topView];
   
}

// 进入抽屉界面
- (void)clickLeftButton
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    AYSSideViewController *sideViewController = [delegate sideViewController];
    [sideViewController showLeftViewController:true];
}



#pragma wark ====================创建topView
- (UIView *)topView
{
    if (!_topView)
    {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
        _topView.backgroundColor = [UIColor blackColor];
        
        _homeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _homeButton.frame = CGRectMake(5, 25, 35, 35);
        [_homeButton setImage:[UIImage imageNamed:@"抽屉菜单"] forState:(UIControlStateNormal)];
        [_homeButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_homeButton addTarget:self action:@selector(clickLeftButton) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.topView addSubview:_homeButton];
        [self getSearchBar];
        [self.view addSubview:_topView];
       
    }
    return _topView;
}

- (void)clickCancleButton
{
    // 判断在添加完视图以后在进行该操作
    if (self.view.subviews.count == 3)
    {
        [self.view.subviews[2] removeFromSuperview];
    }
    [_searchBar resignFirstResponder];
}

#pragma wark ===================searchBar的相关设置
- (void)getSearchBar
{
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(60, 25, SCREEN_WIDTH - 110, 30)];
    // 设置搜索框的占位符
    [self.searchBar setPlaceholder:@"输入影片名"];
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.cornerRadius = 11;
    self.searchBar.backgroundColor = [UIColor clearColor];
    [self.topView addSubview:_searchBar];
    _cancleButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _cancleButton.frame = CGRectMake(SCREEN_WIDTH - 55, 25, 50, 30);
    [_cancleButton setTitle:@"取消" forState:(UIControlStateNormal)];
    _cancleButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_cancleButton addTarget:self action:@selector(clickCancleButton) forControlEvents:(UIControlEventTouchUpInside)];
   [self.topView addSubview:self.cancleButton];

   // 设置代理
    _searchBar.delegate = self;
    
    
}

//点击搜索按钮触发的功能
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 根据数据库表的结构插入对应的model
    [_dataBase executeUpdate:@"INSERT INTO HISTORY (title) VALUES (?)", searchBar.text];
    
    [_searchArr removeAllObjects];
    NSString *searBarText1 =  [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"http://doukan.sinaapp.com/api/tip/?sys_ver=9.1&cli=iphone&q=%@&ver=2.3.4", searBarText1];
    [AYSRequestManager requestWithType:GET url:urlStr parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *dataArr = dic[@"data"];
        for (NSDictionary *dataDic in dataArr)
        {
            AYSHomeSearchBarModel *model = [[AYSHomeSearchBarModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_searchArr addObject:model];
            NSLog(@"searchModel %@", model.q);
            
        }
        // 刷新数据
        _searchBarVC.searchArr = _searchArr;
        [_searchBarVC.tableView reloadData];
        UILabel *promptLable = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT / 2 - 100, 150, 30)];
        if (_searchBarVC.searchArr.count == 0)
        {
            
            promptLable.backgroundColor = [UIColor clearColor];
            promptLable.text = @"无结果";
            promptLable.textColor = [UIColor lightGrayColor];
            promptLable.font = [UIFont systemFontOfSize:22];
            [_searchBarVC.tableView addSubview:promptLable];
        }
        
        
    } error:^(NSError *error)
     {
         NSLog(@"搜索网络请求失败");
     }];
    // 回收键盘
    [searchBar resignFirstResponder];


}

// 开始输入文本
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    _searchBarVC = [[AYSHomeSearchBarTableVC alloc] init];
    _searchBarVC.navigationController = self.navigationController;
    [self.view addSubview:_searchBarVC.view];
    
}


#pragma wark ===================创建tableView
- (void)getMainTableView
{
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.rowHeight = 40;
    _mainTableView.backgroundColor = [UIColor colorWithWhite:0.667 alpha:0.750];
    [self.view addSubview:_mainTableView];
    // 注册
    [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    _mainTableView.showsVerticalScrollIndicator = NO;
    // 设置表头
    _views = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    nameLabel.text = @"搜索记录";
    nameLabel.textColor = [UIColor lightGrayColor];
    [_views addSubview:nameLabel];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 80, 12, 25, 25)];
    imageView.image = [UIImage imageNamed:@"删除"];
    [_views addSubview:imageView];
    
    UIButton *cancleBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [cancleBut setTitle:@"删除" forState:(UIControlStateNormal)];
    cancleBut.frame = CGRectMake(SCREEN_WIDTH - 50, 10, 50, 30);
    [cancleBut setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [cancleBut addTarget:self action:@selector(cancleSQLite) forControlEvents:(UIControlEventTouchUpInside)];
    [_views addSubview:cancleBut];
    
    _mainTableView.tableHeaderView = _views;
}

- (void)cancleSQLite
{
    [self.historyArr removeAllObjects];
    [_dataBase executeUpdate:@"DELETE FROM HISTORY"];
    [self.mainTableView reloadData];
}


#pragma wark ======================配置数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _historyArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.text = self.historyArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AYSHomeSDViewController *searchDetialVC = [[AYSHomeSDViewController alloc] init];
    // 传值
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    searchDetialVC.tableViewText = cell.textLabel.text;
    searchDetialVC.navigationController = self.navigationController;
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    [self.navigationController pushViewController:searchDetialVC animated:YES];
}


#pragma wark ==========数据库的使用
- (void)useSQLite
{
    // 创建保存数据的文件
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"AYSHistory.db"];
    // 根据路径设置打开文件 不存在则创建这个文件
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"filePath===========%@", filePath);
    if ([_dataBase open])
    {
        NSLog(@"数据库打开成功");
        // 创建数据库表
        [_dataBase executeUpdate:@"CREATE TABLE HISTORY (title text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    // 根据查找语句查找表里面的内容
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM HISTORY"];
    while ([resultSet next])
    {
        NSString *title = [resultSet stringForColumn:@"title"];
        [self.historyArr addObject:title];
    }
    // 去除数组中相同的元素
    for (int i = 0; i < self.historyArr.count; i++)
    {
        
        for (int j = (int)self.historyArr.count - 1; j > i; j--)
        {
            if ( [self.historyArr[i] isEqualToString:self.historyArr[j]])
            {
                [self.historyArr removeObjectAtIndex:j];
                
            }
        }
    }

    [resultSet close];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
